<?php
class Home extends CI_Controller{
	function __construct(){
		parent::__construct();
	}
	function index(){
		$data = array();
		$entryId = get_cookie('entry');
		if(!empty($entryId)){
			$data = $this->_buildData($entryId);
			$this->load->view('restaurantList', $data);
		}else{
			$this->load->model('location_model');
			$data['css'][0] = "<link type='text/css' rel='stylesheet' href='/css/home.css'>";
			$data['title'] = '送饭啦';
			$data['query'] = $this->location_model->findHot();
			$this->load->view('home',$data);
		}
	}
	
	function clear(){
		$_COOKIE['entry'] = null;
		delete_cookie('entry');
		$this->index();
	}

	function search(){
		$addressName = $this->input->post('kw');
		$this->load->model('location_model');
		$data['title'] = '地址列表';
		$data['entrys'] = $this->location_model->findByName($addressName);
		$this->load->view('entryList', $data);
	}

	function entry(){
		$data = array();
		$segments = $this->uri->uri_to_assoc();
		$entryId = $segments['at'];
		$data = $this->_buildData($entryId);
		set_cookie('entry', $entryId, time()+86400);
		$this->load->view('restaurantList', $data);
	}
	
	function _buildData($entryId){
		$this->load->model('restaurant_model');
		$this->load->model('location_model');
		$this->load->model('label_model');
		$data['css'][0] = "<link type='text/css' rel='stylesheet' href='/css/restaurantList.css'>";
		$data['css'][1] = "<link type='text/css' rel='stylesheet' href='/css/jquery.rater.css'>";
		$data['entry'] = $this->location_model->findById($entryId);
		$data['title'] = $data['entry']['name'];
		$dataArray = $this->restaurant_model->findByLocation($entryId);
		$labels = $this->label_model->findAll();
		$data['rsts'] = $dataArray;
		$data['labels'] = $labels;
		$data['filterJson'] = $this->_buildFilterJson($dataArray, $labels, $entryId);
		return $data;
	}

	function _buildFilterJson($dataArray,$labels, $entryId){
		$filter = array();
		$open = array();
		$compensate = array();
		$promotion = array();
		$all = array();
		foreach ($dataArray as $row){
			$all[] = (int)$row['id'];
			if($row['isOpen']){
				$open[] = (int)$row['id'];
			}
			if($row['isCompensate']){
				$compensate[] = (int)$row['id'];
			}
			if($row['isPromotion']){
				$promotion[] = (int)$row['id'];
			}
		}
		$filter['all'] = $all;
		$filter['open'] = $open;
		$filter['compensate'] = $compensate;
		$filter['promotion'] = $promotion;
		foreach ($labels as $row){
			$key = $row['alias'];
			$filter["$key"] = $this->restaurant_model->getRstsIdByLabel($row['id'],$entryId);
		}
		
		return json_encode($filter);
		
	}

	function autoComplete(){

	}
}
?>